<template>

    <div>
        <!--搜索区域-->
        <div class="search">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                <el-form-item label="角色名">
                    <el-input v-model="searchForm.name" placeholder="请输入角色名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="searchSubmit">查询</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!--头部工具区域-->
        <div class="head-btn">
            <el-button type="primary" @click="showAddRoleForm">添加</el-button>
        </div>
        <!--表格数据区域-->
        <div class="table-data">
            <el-table
                :data="tableData"
                style="width: 100%">
                <el-table-column label="角色名">
                    <template slot-scope="scope">
                        <span>{{ scope.row.name }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="角色权限字符">
                    <template slot-scope="scope">
                        <span>{{ scope.row.roleEn }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="描述">
                    <template slot-scope="scope">
                        <span>{{ scope.row.remark }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="角色状态">
                    <template slot-scope="scope">
                        <el-switch
                            @change="changeRoleState(scope.row)"
                            v-model="scope.row.available"
                            active-color="#13ce66"
                            :active-value="1"
                            :inactive-value="0"
                            inactive-color="#ff4949">
                        </el-switch>
                    </template>

                </el-table-column>

                <el-table-column label="创建时间" width="150px">
                    <template slot-scope="scope">
                        <span>{{ scope.row.createtime }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="280px">
                    <template slot-scope="scope">
                        <el-button
                            icon="el-icon-edit"
                            size="mini"
                            @click="handleEdit(scope.$index, scope.row)">
                        </el-button>

                        <el-popconfirm title="确定删除吗？" @confirm="deleteRole(scope.$index, scope.row)">
                            <el-button
                                slot="reference"
                                size="mini"
                                type="danger"
                                icon="el-icon-delete">
                            </el-button>
                        </el-popconfirm>
                        <el-button
                            size="mini"
                            type="success"
                            @click="handleAuth(scope.$index, scope.row)">分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!--分页区域-->
        <div class="page">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="searchForm.currentPage"
                :page-sizes="[5,10,15,20]"
                :page-size="searchForm.limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total=total>
            </el-pagination>
        </div>

        <!--添加 编辑用户信息弹窗-->
        <el-dialog :title="dialogTitle" :visible.sync="addRoleFormVisible" width="50%" @close="clearInfo">
            <el-form :model="roleForm" ref="roleInfo" :rules="roleRules" label-width="90px" size="medium">
                <el-input v-model="roleForm.id" autocomplete="off" v-show="false"></el-input>
                <el-form-item label="角色名" prop="name">
                    <el-input v-model="roleForm.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="权限字符" prop="roleEn">
                    <el-input v-model="roleForm.roleEn" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="remark">
                    <el-input v-model="roleForm.remark" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addRoleInfo">确 定</el-button>
            </div>
        </el-dialog>

        <!--分配权限-->
        <el-dialog title="分配权限" :visible.sync="authTreeVisible" width="30%" @close="clearTree">
            <el-tree
                ref="tree"
                :data="treeData"
                show-checkbox
                node-key="id"
                :default-expand-all="true"
                :default-checked-keys="defaultCheckedKeys"
                :props="defaultProps">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addRolePermissions">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {
    addOrUpdateRole, addRolePermission,
    deleteRoleById,
    getAuthTree,
    getRoleById,
    getRoleList,
    getRolePermissionById,
    updateRoleState
} from "@/request/api";
import {listToTree} from "@/util/treeUtil";

export default {
    name: "RoleView",
    data() {
        return {
            roleId: '',
            searchForm: {
                limit: 5,
                currentPage: 1
            },
            tableData: [],
            total: 20,
            dialogTitle:'',
            addRoleFormVisible: false,
            roleForm:{},
            roleRules:{
                name: [{required: true, message: '请输入角色名', trigger: 'blur'}],
                roleEn: [{required: true, message: '请输入权限字符', trigger: 'blur'}],
                remark: [{required: true, message: '请输入描述信息', trigger: 'blur'}],
            },
            authTreeVisible: false,
            treeData: [],
            defaultCheckedKeys:[],
            defaultProps:{
                children:'children', // 层级包含关系名字
                label:'label' // 树形节点名字
            }
        }
    },
    methods:{
        searchSubmit(){
            this.list()
            this.searchForm = {
                limit: 5,
                currentPage: 1
            }
        },
        showAddRoleForm(){
            this.dialogTitle = '添加角色'
            this.addRoleFormVisible = true
        },
        handleEdit(index, row){
            this.addRoleFormVisible = true
            this.dialogTitle = '编辑角色'
            console.log(row.id)
            // 信息回显
            getRoleById(row.id).then(response=>{
                this.roleForm = response.data
            })
        },
        deleteRole(index, row){
            deleteRoleById(row.id).then(response=>{
                if(response.code===200){
                    this.$message.success(response.msg)
                    this.searchForm={
                        limit: 5,
                        currentPage: 1
                    }
                    this.list()
                    return
                }
                this.$message.warning(response.msg)
            }).catch(error=>{
                this.$message.error("请求失败")
            })
        },
        async handleAuth(index, row){
            this.authTreeVisible = true
            this.roleId = row.id
            let {data} = await getAuthTree()  // 权限列表
            // 遍历处理
            let permissions = data.map(p=>{
                return {
                    label: p.title,
                    id: p.id,
                    pid: p.pid

                }
            })
            this.treeData = listToTree(permissions)
            // 角色权限回显
            console.log(row.id)
            let {data:btnPermission} = await getRolePermissionById(row.id)
            this.defaultCheckedKeys = btnPermission
        },
        handleSizeChange(val){
            this.searchForm.limit = val
            this.list()
        },
        handleCurrentChange(val){
            this.searchForm.currentPage = val
            this.list()
        },
        // 改变角色状态
        changeRoleState(row){
            updateRoleState({id:row.id,available:row.available}).then(response=>{
                if(response.code===200){
                    this.$message({
                        type:'success',
                        message:response.msg,
                        onClose:()=>{
                            this.list()
                        }
                    })
                    return
                }
                this.$message.warning(response.msg)
                this.list()
            }).catch(error=>{
                this.$message.error("请求失败")
            })
        },
        clearInfo(){
            this.roleForm={}
            this.$refs.roleInfo.clearValidate()
        },
        addRoleInfo(){
            this.$refs.roleInfo.validate(valid=>{
                if(!valid){
                    this.$message.warning("请填写完整信息")
                    return
                }
                console.log(this.roleForm)
                // 发送异步请求
                
                addOrUpdateRole(this.roleForm).then(response=>{
                    if(response.code === 200){
                        this.$message.success(response.msg)

                        this.addRoleFormVisible = false
                        this.roleForm={}
                        this.list()
                        return
                    }
                    this.$message.error(response.msg)
                }).catch(error=>{
                    this.$message.error("请求失败")
                })
            })

        },
        clearTree(){},
        addRolePermissions(){
            this.authTreeCheckedKeys = [...this.$refs.tree.getHalfCheckedKeys(), ...this.$refs.tree.getCheckedKeys()]
            // 获取角色id
            let roleId = this.roleId
            let ids = this.authTreeCheckedKeys
            if(ids.length===0){
                this.$message.warning("请给角色分配权限")
            }
            // 发生异步请求
            addRolePermission({roleId,ids}).then(response=>{
                if(response.code === 200){
                    this.$message.success(response.msg)
                    this.authTreeVisible = false
                    this.defaultCheckedKeys=[]
                    return
                }
                this.$message.warning(response.msg)
            }).catch(error=>{
                this.$message.error("请求失败")
            })


        },
        list(){
            getRoleList(this.searchForm).then(response=>{
                if(response.code===200){
                    this.tableData = response.data.pageData
                    this.total = response.data.total
                    return
                }

                this.$message.warning(response.msg)
            }).catch(error=>{
                this.$message.error("请求失败")
            })
        }
    },
    created() {

        this.list()
    }
}
</script>

<style scoped>
.search {
    padding: 10px;
    border-bottom: 1px solid #eee;
}
.head-btn, .page {
    padding-top: 15px;
    padding-bottom: 10px;
}
</style>